package org.kukker.view;

import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Map;

import org.kukker.R;
import org.kukker.Util;
import org.kukker.event.Event;

import android.content.Context;
import android.graphics.Rect;
import android.text.util.Linkify;
import android.util.AttributeSet;
import android.util.Log;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.webkit.WebView;
import android.widget.FrameLayout;
import android.widget.ScrollView;
import android.widget.TextView;

public class EventDetailView extends ScrollView{
	
	private TextView name;
	private TextView description;
	
	private TextView dayAndDate;
	private TextView endDate;
	
	private TextView startTime;
	private TextView endTime;
	
	private TextView venueName;
	private TextView venueAddress;
	private TextView venueCity;
	private TextView venueCountry;
	
	private WebView webview;
	
	private TextView url;
	
	//TODO refactor eventdetail clicking detection 
	
	private boolean cd_isMoved;
	
	
	public EventDetailView(Context context) {
		super(context);
		this.init();
		this.initLookAndFeel();
	}
	
	
	public EventDetailView(Context context, AttributeSet attrs, Map inflateParams) {
        super(context, attrs, inflateParams);
        this.init();
	}
	
	private void init(){
		
		this.name = (TextView) findViewById(R.id.eventdetail_eventname);
		this.description = (TextView) findViewById(R.id.eventdetail_eventdescription);
		this.startTime = (TextView) findViewById(R.id.eventdetail_starttime);
		this.endTime = (TextView) findViewById(R.id.eventdetail_endtime);
		this.dayAndDate = (TextView) findViewById(R.id.eventdetail_dayanddate);
		this.venueName = (TextView) findViewById(R.id.eventdetail_venuename);
		this.venueAddress = (TextView) findViewById(R.id.eventdetail_venueaddress);
		this.venueCity = (TextView) findViewById(R.id.eventdetail_venuecity);
		this.venueCountry = (TextView) findViewById(R.id.eventdetail_venuecountry);
		//this.webview = (WebView)findViewById(R.id.eventdetail_webview);
		
		
		this.url = (TextView) findViewById(R.id.eventdetail_url);
		
		
		//this.url.
		//Linkify.addLinks(this.url, Linkify.WEB_URLS);
		
	}
	
	private void initLookAndFeel(){
		
	}
	
	
	public void setName(String text){
		this.name.setText(text);
	}
	public void setDescription(String text){		
		this.description.setText(text);
		this.description.setClickable(true);
		Linkify.addLinks(this.description, Linkify.ALL);
	}
	public void setDayAndDate(String text){
		this.dayAndDate.setText(text);
	}
	public void setStartTime(String text){
		this.startTime.setText(text);
	}
	public void setEndTime(String text){
		this.endTime.setText(text);
	}
	public void setVenueName(String text){
		this.venueName.setText(text);
	}
	
	public void setVenueAddress(String text){
		this.venueAddress.setText(text);
	}
	
	
	public void setVenueCity(String text){
		this.venueCity.setText(text);
	}
	public void setVenueCountry(String text){
		this.venueCountry.setText(text);
	}
	
	public void setUrl(String text){
		this.url.setText(text);
		Linkify.addLinks(this.url, Linkify.WEB_URLS);
	}
	
	public boolean onTouchEvent(MotionEvent event){
		
		super.onTouchEvent(event);//important
		
		
		 String actionName = org.kukker.Util.kMotionEvent.getActionName(event);
		 Log.i("eventflow1",
   			"["+this.getClass().getSimpleName()+"]" +
   			
   			"["+
   			"isSelected:"+this.isSelected()+
   			", focused:"+this.isFocused() +
   			"]"
   			
   			+"["
   			+"onTouchEvent()"
   		
   			+", action:"+actionName
   			
   			+"]"
   			
		 );
		 int action = event.getAction();
		 
		 
		 if(action == MotionEvent.ACTION_DOWN){
			 this.cd_isMoved = false;

			 return true;
			 
		 }
		 else if(action == MotionEvent.ACTION_UP){
			 if(!this.cd_isMoved){
				 this.cd_isMoved = false;
			 long downTime = event.getDownTime();
			 long upTime = event.getEventTime();
			 long duration = upTime - downTime;			 
			 long clickLB = 80;
			 long clickUB = 1000;			 
			 Log.i("debug","duration: "+duration);
			 if(duration > clickLB && duration < clickUB){
				 Log.i("debug","eventdetail clicked");
				 this.mEventDetailViewListener.onClick();
			 }			 
			 }
			 return true;
		 }
		 else if(action ==MotionEvent.ACTION_MOVE){
			 this.cd_isMoved = true;			 
		 }
		 //this.setSelected(true);
		 return false;
	}
	
	
	public boolean onKeyDown(int keyCode, KeyEvent event){		
		boolean res = super.onKeyDown(keyCode, event); //important
		
		Log.i("eventflow1",
    			"["+this.getClass().getSimpleName()+"]" +
    			
    			"["+
    			"isSelected:"+this.isSelected()+
    			"]"
    			
    			+"["
    			+"onKeyDown() " +
    			",keyCode:"+keyCode
    			
    			+"]"    			
    	);
		
		if(keyCode == KeyEvent.KEYCODE_DPAD_LEFT){
			
			
			//since we want to detect on key up later we have to stop this event from propagating.
			//stop propagating 
			return true;
		}
		
		if(keyCode == KeyEvent.KEYCODE_DPAD_RIGHT){
			//since we want to detect on key up later we have to stop this event from propagating.
			//so that the next keyup event will be handled by this object.
			return true;
		}
		
		if(keyCode == KeyEvent.KEYCODE_DPAD_CENTER){	
			//since we want to detect on key up later we have to stop this event from propagating.
			//so that the next keyup event will be handled by this object.
			return true;		
		}else{
					
			View v = this.findFocus();
			if(v!=null){
				Log.i("debug",this.getClass().getSimpleName()+", found focus: "+v.getClass().getSimpleName());
				v.requestFocus();
			}
			
		}
		
		return false; // do not consume event  for other keys
    	
	}
	
	

	public boolean onKeyUp(int keyCode, KeyEvent event){		
		boolean res = super.onKeyUp(keyCode, event); //important
		
		Log.i("eventflow1",
    			"["+this.getClass().getSimpleName()+"]" +
    			
    			"["+
    			"isSelected:"+this.isSelected()+
    			"]"
    			
    			+"["
    			+"onKeyUp() " +
    			",keyCode:"+keyCode
    			
    			+"]"    			
    	);
		
		if(keyCode == KeyEvent.KEYCODE_DPAD_LEFT){
			
			
			//since we want to detect on key up later we have to stop this event from propagating.
			//stop propagating 
			return true;
		}
		
		if(keyCode == KeyEvent.KEYCODE_DPAD_RIGHT){
			//since we want to detect on key up later we have to stop this event from propagating.
			//so that the next keyup event will be handled by this object.
			

			mEventDetailViewListener.onKeyRightUp();			
			
			return true;
		}
		
		if(keyCode == KeyEvent.KEYCODE_DPAD_CENTER){	
			//since we want to detect on key up later we have to stop this event from propagating.
			//so that the next keyup event will be handled by this object.

			mEventDetailViewListener.onClickDCenter();
			return true;		
		}
		
		return res;    	
	}
	
	public void onFocusChanged(boolean gainFocus, int direction,
			Rect previouslyFocusedRect) {

		Log.i("eventflow1",

		"[" + this.getClass().getSimpleName() + "]" +

		"[" + "isSelected:" + this.isSelected() + "]"

		+ "[" + "onFocusChanged()" + ", gainFocus:" + gainFocus
				+ ", direction:" + direction + "]"

		);
		
		
		
		if (gainFocus) {
			//this.setFocusable(false);
			boolean focusTaken = this.requestFocus(View.FOCUS_DOWN);
						
			//View whoHasFocus = this.findFocus();
			
			View aView = this.focusSearch(View.FOCUS_DOWN);
			
			if(aView != null){
				aView.requestFocus();
				aView.setSelected(true);
				//EventView view2 = (EventView)whoHasFocus;			
				Log.i("eventflow1",this.getClass().getSimpleName()+", focus is passed to :" + aView.toString()
				+", focusTaken:"+focusTaken		
				);
						//+", position:"+view2.getPosition());
			}
			
		
		} else {
			//this.setFocusable(false);
		}
		

	}
	
	public void populateEventDetailsView(Event event){
		//event = event.dataNotNull();
		this.init();
		if(this.name == null){
			Log.i("error","name is null");
			
		}
		
		try{		
			this.setName(event.name);
			this.setDescription(event.description);
			this.setDayAndDate(event.startDate);
			this.setStartTime(event.startTime);//
			this.setEndTime(event.endTime);
			this.setVenueName(event.venueName);
			this.setVenueAddress(event.venueAddress);
			this.setVenueCity(event.venueCity);//
			this.setVenueCountry(event.venueCountry);
			this.setUrl(event.url);
			/*
			String cd = "<html><body style=\"background-color=#ff000;\"><div>"+event.description+"</div></body></html>"; 
			//String cd2 =URLEncoder.encode("cd","utf-8");
			this.webview.loadData(cd, "text/html", "utf-8");
			this.webview.invalidate();
			this.webview.reload();
			!/
			
			
			/*
			this.webview.loadData(
                     "<html><body>Can I focus?<br /><a href=\"#\">No I cannot!</a>.</body></html>",
                     "text/html", "utf-8");
*/
			
			//ArrayList<View> views = this.description.getFocusables();
			//int num = views.size();
			Log.i("debug","edv");
			
		}catch(Exception e){
			Log.e("error","populateEventDetailsView:" + e.getMessage()+" ");
		}
	}
	
	public void updateView(Event event){
		
		
		
	}
	
	public interface IEventDetailViewListener {
		public void onKeyRightUp();
		public void onClick();
		public void onClickDCenter();
	}
	
	private IEventDetailViewListener mEventDetailViewListener;
	public void setListener(IEventDetailViewListener listener){
		this.mEventDetailViewListener = listener;
		
	}
	
	public void setDetectIncomingEvents(boolean state){
		
			//
			this.setClickable(state);
			this.setFocusable(state);
			this.setFocusableInTouchMode(state);
			//this.setBlockChildEvents(!state);
			this.setBlockDescendantFocus(!state);//blocks or ignoring focus from a key down
			this.setEnabled(state);
			//
			if(!state){
				View v = this.findFocus();
				if(v!=null){v.clearFocus();}
				}
	}
	
	
}